/* 
 * @author : Amissah Gideon<kuulmek@yahoo.com>
 * @version 1.0
 */

var gblFields = [
    'property_group_id',
    'location_id',
    'property_group_type_id',
    'property_group_sub_type_id'
]

var ModifyBill = {
    
    /* Server script url   */
	ssUrl : '',
    selected_row_id : null,
    component_row_id : null,
    component_tr : null,
    billTotal : 0,

   /* dataTable Object */
    objGrid: null,
    
    init:function(){ //console.log(gblPrpGroupData)      
	  var dataUrl = $('#table-url').val();
      ModifyBill.objGrid = $('#billflex').flexigrid({
            url: dataUrl,
        	dataType: 'json',
            colModel : [
                {display: 'ID', name : 'id', width : 20, sortable : false, align: 'left', hide:true},                
                {display: 'Property Group', name : 'group_name', width : 200, sortable : false, align: 'center', hide:false},
                {display: 'Location', name : 'location_name', width : 130, sortable : false, align: 'center', hide:false},
                {display: 'Property Type', name : 'type_name', width : 130, sortable : false, align: 'center', hide:false},
                {display: 'Property Sub Type', name : 'sub_type_name', width : 130, sortable : false, align: 'center', hide:false},
                {display: 'Year', name : 'year', width : 90, sortable : false, align: 'center', hide:false},
                {display: 'Bill Total '+CURRENCY, name : 'totals', width : 90, sortable : false, align: 'center', hide:false}
        	],
            formFields : [
        		{type:'buttom',name: 'Add', bclass: 'add',onpress : ModifyBill.handleGridEvent},
        		//{separator: true},
                //{type:'buttom',name: 'Edit', bclass: 'edit',onpress : ModifyBill.handleGridEvent},
                {separator: true},
        		{type:'buttom',name: 'Delete', bclass: 'delete',onpress : ModifyBill.handleGridEvent},
                {separator: true},
                {type:'buttom',name: 'View', bclass: 'view',onpress : ModifyBill.handleGridEvent},
                {separator: true},
                {type:'buttom',name: 'Bill Components', bclass: 'add_componenet',onpress : ModifyBill.handleGridEvent},
                {separator: true},
                {type:'buttom',name: 'Apply Bill', bclass: 'apply_bill',onpress : ModifyBill.handleGridEvent},
                {separator: true},
                {type:'buttom',name: 'Print Bill', bclass: 'print',onpress : ModifyBill.handleGridEvent},
       		],
            checkboxSelection: true,
            columnControl:true,
        	sortname: "id",
        	sortorder: "desc",
        	usepager: true,
        	title: 'List of Bills',
        	useRp: true,
        	rp: 15,
        	showTableToggleBtn: false,
        	width: 913,
        	height: 200
      });
      
       jLib.afterClosePopUpForm('bill-form',function(){
         ModifyBill.selected_row_id = null;
       });
       $("#bill-form").validationEngine(); 
      
       $('#bill-save-btn').click(function(){
           ModifyBill.saveBill();
       });
       $('#bill-cancel-btn').click(function(){
           document.getElementById('bill-form').reset();
           $.validationEngine.closePrompt('.formError',true);
           $.colorbox.close();
           ModifyBill.selected_row_id = null;
       });
       $('#bill-ok-btn').click(function(){
           $.colorbox.close();
       }); 
       $('.date-picker').datepicker({
            autoSize:true,
            dateFormat: 'yy-mm-dd',
            showWeek: false,
            firstDay: 0,
            showOn: 'button',
            buttonImage: 'img/calender.png',
            buttonImageOnly: true,
            changeMonth: true,
            changeYear: true,
            minDate: new Date(1920, 1, 1)
       });
       
       ModifyBill.initializeFormSelectChange();
       
       // Bill Components *******************//////////
       
       $("#bill-component-form").validationEngine();
       $('#bill-component-save-btn').click(function(){
           ModifyBill.saveBillComponent();
       });
       $('#bill-component-cancel-btn').click(function(){
           document.getElementById('bill-component-form').reset();
           $.validationEngine.closePrompt('.formError',true);
           //$.colorbox.close();
           ModifyBill.component_row_id = null;
           ModifyBill.component_tr = null;
       });
       jLib.afterClosePopUpForm('bill-component-form',function(){
           ModifyBill.selected_row_id = null;
           ModifyBill.component_row_id = null;
           ModifyBill.component_tr = null;
       });
       
       $('#list-table-data tbody tr td a.edit').live('click',function(){
            ModifyBill.component_tr = $(this).parent().parent();
            ModifyBill.component_row_id = parseInt($(this).parent().parent().attr('data-id'));
            var comp_name = $(this).parent().prev().prev().text();
            var amount = $(this).parent().prev().text();
            $('#bill-component-form  #comp_name').val(comp_name);
            $('#bill-component-form  #amount').val(amount);
            //Location.objStatus = 'edit';
       });
       $('#list-table-data tbody tr td a.delete').live('click',function(){
            ModifyBill.component_tr = $(this).parent().parent();
            ModifyBill.deleteBillComponent(parseInt($(this).parent().parent().attr('data-id')));
       });
       
       /////////////////////*************** Apply Bill ************//////////////////
       var chkSelector = ' tr td:nth-child(1) :checkbox';
       $('#apply_checker').live('click',function(){
        	$('table#applybill-table-data ' + chkSelector)
      		.attr('checked', $(this).attr('checked'));	
       });
       $('#apply-bill-btn').live('click',function(){
           ModifyBill.doApplyBill('apply');
       });
       $('#remove-bill-btn').live('click',function(){
           ModifyBill.doApplyBill('unapply');
       });
       
       /////////////////////*************** Print Bill ************//////////////////
       var chkSelector = ' tr td:nth-child(1) :checkbox';
       $('#print_checker').live('click',function(){
        	$('table#print-table-data ' + chkSelector)
      		.attr('checked', $(this).attr('checked'));	
       });
       $('#print-bill-btn').live('click',function(){
           ModifyBill.doPrintBill();
       });
	},
    
    handleGridEvent: function(com, grid, value){
		if (com == 'Add') {
		   $.colorbox({
                inline:true,
                scrolling:false,
                overlayClose:false,
                escKey:false,
                top:'5%',
                title:'Bill Information',
                href:"#bill-form-window",
            });
		} 
        else if (com == 'Edit') {
          if(jLib.rowSelectedCheck(grid,1)){
               ModifyBill.editBill(jLib.getSelectedRowIds(grid));
          }
		}
        else if (com == 'Delete') {
            if(jLib.rowSelectedCheck(grid)){
                   	ModifyBill.deleteBill(grid);
            }
		}
        else if (com == 'View') {
            if(jLib.rowSelectedCheck(grid,1)){
                   	ModifyBill.viewBill(jLib.getSelectedRowIds(grid));
            }
		}
        else if (com == 'Bill Components') {
            if(jLib.rowSelectedCheck(grid,1)){
                   	ModifyBill.billComponent(jLib.getSelectedRowIds(grid));
            }
		}
        else if (com == 'Apply Bill') {
            if(jLib.rowSelectedCheck(grid,1)){
                   	ModifyBill.applyBill(jLib.getSelectedRowIds(grid));
            }
		}
        else if (com == 'Print Bill') {
            if(jLib.rowSelectedCheck(grid,1)){
                   	ModifyBill.printBill(jLib.getSelectedRowIds(grid));
            }
		}
   },
   
   
   editBill:function(row_ids){
     var load_id = row_ids[0];
     var url = $('#load-url').val();
     var query = 'ids=' + load_id;
     $.post(url, query, function(response){  
		if(response.code === 0){
		   var dataBill = response.data.Bill;
           var dataLocation = response.data.Location;
           var dataGroup = response.data.PropertyGroup;
           var dataGroupType = response.data.PropertyGroupType;
           var dataGroupSubType = response.data.PropertyGroupSubType;
        
           $('#bill-form #property_group_id').val(dataGroup.id);
           ModifyBill.processGroupChange(dataGroup.id);
           ModifyBill.processGroupTypeChange(dataGroupType.id);
           ModifyBill.filterPropertyForm(dataGroup.id);
           $('#bill-form #location_id').val(dataLocation.id); 
           $('#bill-form #property_group_type_id').val(dataGroupType.id);
           $('#bill-form #property_group_sub_type_id').val(dataGroupSubType.id);
           $('#bill-form #year').val(dataBill.year);
           $('#bill-form #description').val(dataBill.description);
          
           ModifyBill.selected_row_id = load_id;
           
            $.colorbox({
                inline:true,
                scrolling:false,
                overlayClose:false,
                escKey:false,
                top:'5%',
                title:'Bill Information',
                href:"#bill-form-window",
            });
		}
		/* When there are Errors */
		else if(response.code === 1){
		   /* Alert the user that the server response*/
		   jLib.setFeedback(response.mesg, 'error_message', false);
		}  
     },'json');
   },
   
   saveBill:function(){
         /* Validate the form*/
          var validationStatus =  $('#bill-form').validationEngine({returnIsValid:true});
           /* When the Validation Status is true meaning that the data input are correct then the data can be processed. */
          if(validationStatus){
                 
                 var query = 'model=ModifyBill&row_id='+ModifyBill.selected_row_id+'&'+$('#bill-form').serialize();
                 /* Send the data to the server and handle the server response */                     
                 $.post( $('#add-edit-url').val(), query, function(response){
					var txt = '';
                    if(typeof response.mesg  == 'object'){
    					for(megTxt in response.mesg){
    						txt += response.mesg[megTxt]+'<br />';
    					}
    				}
    				else{
    					txt = response.mesg
    				}
                    
					if(response.code === 0){					   
					   jLib.setFeedback(txt, 'success_message', false);
                                                  
                       if(ModifyBill.selected_row_id){                            
                            var group_id = parseInt($('#bill-form  #property_group_id').val());
                            var group_type_id = parseInt($('#bill-form  #property_group_type_id').val());
                            var group_sub_type_id = parseInt($('#bill-form  #property_group_sub_type_id').val());
                            
                            var groupName = $("#bill-form  #property_group_id option:selected").text();
                            var groupTypeSetName = $("#bill-form  #property_group_type_id option:selected").text();
                            var groupSubTypeSetName = $("#bill-form  #property_group_sub_type_id option:selected").text();
                            var locationName = $("#bill-form #location_id option:selected").text();
                            var year = $("#bill-form #year").val();
                            
                            update_data = {
                               'group_name': groupName,
                               'location_name': locationName,
                               'type_name': groupTypeSetName,
                               'sub_type_name':groupSubTypeSetName,
                               'year': year
                            };
                            jLib.updateGridData(ModifyBill.objGrid, update_data);
                            jLib.highlightRow(ModifyBill.objGrid);
                       }
                       else{
                            $(ModifyBill.objGrid).flexReload();    
                       }
                       document.getElementById('bill-form').reset();
                       $.validationEngine.closePrompt('.formError',true)
					   $.colorbox.close();
                       ModifyBill.selected_row_id = null;
                       //ModifyBill.property_item_detail_id = null;
                       $('#bill-form #property_group_id').change();
					}
					else if(response.code === 1){
					   jLib.builPopUpPrompt('.bill-prompt',txt,'error',false);
					   jLib.setFeedback(txt, 'error_message', false);
					}
                },'json'); 
          } 
   },
   
   deleteBill:function(grid){
        var url = $('#delete-url').val();
        jLib.do_delete(url,grid);
   },
   
   viewBill:function(row_ids){
     var load_id = row_ids[0];
     var url = $('#load-url').val();
     var query = 'ids=' + load_id;
     $.post(url, query, function(response){  
		if(response.code === 0){
		   var dataBill = response.data.Bill;
           var dataLocation = response.data.Location;
           var dataGroup = response.data.PropertyGroup;
           var dataGroupType = response.data.PropertyGroupType;
           var dataGroupSubType = response.data.PropertyGroupSubType;
           var billTl = response.data.BillTotal;
           
           $('#bill-view-window div.content div.row').each(function(){
                $(this).css('display','block');
           });
           
           var type_name = dataGroupType.type_name ? dataGroupType.type_name :  'All';
           var sub_type_name = dataGroupSubType.sub_type_name ? dataGroupSubType.sub_type_name : 'All';
           var location_name = dataLocation.location_name ? dataLocation.location_name : 'All';
           var description = dataBill.description ? dataBill.description : '&nbsp;';
           $('#bill-view-window div.content div.property_group_id .data').html('&nbsp;'+dataGroup.group_name);
           $('#bill-view-window div.content div.location_id .data').html('&nbsp;'+location_name);
           $('#bill-view-window div.content div.property_group_type_id .data').html('&nbsp;'+type_name);
           $('#bill-view-window div.content div.property_group_sub_type_id .data').html('&nbsp;'+sub_type_name);
           $('#bill-view-window div.content div.year .data').html('&nbsp;'+dataBill.year);
           $('#bill-view-window div.content div.description .data').html('&nbsp;'+description);
           $('#bill-view-window div.content div.total .data').html('&nbsp;'+billTl); 
           //ModifyBill.filterPropertyForm(dataGroup.id);
           var groupData = gblPrpGroupData[dataGroup.id];
           var fields = groupData.fields;
           if(fields.length > 0){
                var diff_arr = jLib.array_diff(fields, gblFields)
                for(var x = 0; x < diff_arr.length; x++){
                    var diff = diff_arr[x];
                    //console.log(diff);
                    $('#bill-view-window div.content div.'+diff+'').css('display','none'); 
                }
           }          
           
           $.colorbox({
                inline:true,
                scrolling:false,
                overlayClose:false,
                escKey:false,
                top:'5%',
                title:'Bill Information',
                href:"#bill-view-window",
            });
           
           $.colorbox.resize();
		}
		/* When there are Errors */
		else if(response.code === 1){
		   /* Alert the user that the server response*/
		   jLib.setFeedback(response.mesg, 'error_message', false);
		}  
     },'json');
   },
   
   
   /////////////  Bill Components *********************** /////////////////////////////////
   billComponent:function(row_ids){
     var load_id = row_ids[0];
     var url = $('#load-url').val();
     var query = 'ids=' + load_id;
     
     $.post(url, query, function(response){  
		if(response.code === 0){
		   var dataBill = response.data.Bill;
           var dataLocation = response.data.Location;
           var dataGroup = response.data.PropertyGroup;
           var dataGroupType = response.data.PropertyGroupType;
           var dataGroupSubType = response.data.PropertyGroupSubType;
           var dataBillComponent = response.data.BillComponent;
           ModifyBill.billTotal = response.data.BillTotal;
           $('#list-table-data tbody').html('');
           
           if(dataBillComponent){
                for(var x=0; x < dataBillComponent.length; x++){
                    var comp_id = dataBillComponent[x]['id'];
                    var comp_name = dataBillComponent[x]['comp_name'];
                    var amount = dataBillComponent[x]['amount'];
                    
                    var txt_tr = "<tr data-id='"+comp_id+"'>";
                    txt_tr +=  "<td align='center'>"+comp_name+"</td>";
                    txt_tr +=  "<td align='center'>"+amount+"</td>";
                    txt_tr +=  "<td colspan='2' align='center'>";
                    txt_tr +=       "<a href='javascript:void(0)' type='edit' class='edit'>edit</a> &nbsp;&nbsp;|&nbsp;&nbsp;";
                    txt_tr +=       "<a href='javascript:void(0)' type='delete' class='delete'>delete</a>";
                    txt_tr +=  "</td>";
                    txt_tr +="</tr>";
                    
                    $('#list-table-data tbody').prepend(txt_tr);
               }
           }
          
           ModifyBill.selected_row_id = load_id;
           
            $.colorbox({
                inline:true,
                scrolling:false,
                overlayClose:false,
                escKey:false,
                top:'5%',
                title:'Bill Component Information',
                href:"#bill-component-form-window",
            });
            $.colorbox.resize();
		}
		/* When there are Errors */
		else if(response.code === 1){
		   /* Alert the user that the server response*/
		   jLib.setFeedback(response.mesg, 'error_message', false);
		}  
     },'json');
   },
   
   
   saveBillComponent:function(){
         /* Validate the form*/
          var validationStatus =  $('#bill-component-form').validationEngine({returnIsValid:true});
           /* When the Validation Status is true meaning that the data input are correct then the data can be processed. */
          if(validationStatus){
                 var query = 'model=BillComponent&row_id='+ModifyBill.selected_row_id+'&upt_id='+ModifyBill.component_row_id+'&'+$('#bill-component-form').serialize();
                 /* Send the data to the server and handle the server response */                     
                 $.post( $('#add-edit-url').val(), query, function(response){
					var txt = '';
                    if(typeof response.mesg  == 'object'){
    					for(megTxt in response.mesg){
    						txt += response.mesg[megTxt]+'<br />';
    					}
    				}
    				else{
    					txt = response.mesg
    				}
                    
					if(response.code === 0){
					   jLib.setFeedback(txt, 'success_message', false);
                       var comp_name = $('#bill-component-form  #comp_name').val();
                       var amount =    parseFloat($('#bill-component-form  #amount').val()).formatMoney(2, '.', ',');
                                   
                       if(ModifyBill.component_row_id){                            
                          
                          $(ModifyBill.component_tr).find('td:nth-child(1)').html(comp_name); 
                          $(ModifyBill.component_tr).find('td:nth-child(2)').html(amount);  
                       }
                       else{
                            var txt_tr = "<tr data-id='"+response.data_id+"'>";
                            txt_tr +=  "<td align='center'>"+comp_name+"</td>";
                            txt_tr +=  "<td align='center'>"+amount+"</td>";
                            txt_tr +=  "<td colspan='2' align='center'>";
                            txt_tr +=       "<a href='javascript:void(0)' type='edit' class='edit'>edit</a> &nbsp;&nbsp;|&nbsp;&nbsp;";
                            txt_tr +=       "<a href='javascript:void(0)' type='delete' class='delete'>delete</a>";
                            txt_tr +=  "</td>";
                            txt_tr +="</tr>";
                            
                            $('#list-table-data tbody').prepend(txt_tr);
                       }
                       
                       ModifyBill.billTotal = parseFloat(response.billTotal).formatMoney(2, '.', ',');
                       update_data = {
                           'totals': response.billTotal
                       };
                       jLib.updateGridData(ModifyBill.objGrid, update_data);
                       
                       document.getElementById('bill-component-form').reset();
                       $.validationEngine.closePrompt('.formError',true)
					   //$.colorbox.close();
                       ModifyBill.component_row_id = null;
                       ModifyBill.component_tr = null;
                       
                       jLib.builPopUpPrompt('.bill-component-prompt',txt,'pass',false);
					}
					else if(response.code === 1){
					   jLib.builPopUpPrompt('.bill-component-prompt',txt,'error',false);
					   jLib.setFeedback(txt, 'error_message', false);
					}
                },'json'); 
          } 
   },
   
   deleteBillComponent:function(id){
        var url = $('#delete-component-url').val();
        var query = 'id='+id;
        jConfirm('Are you sure you want to continue ?', 'Confirm', function(confirmation) {
            if(confirmation){
                $.post(url, query, function(response){
                   if(response.code === 0){
                         ModifyBill.billTotal = parseFloat(ModifyBill.billTotal - parseFloat($(ModifyBill.component_tr).find('td:nth-child(2)').text())).formatMoney(2, '.', ',');
                         update_data = {
                           'totals': ModifyBill.billTotal
                         };
                         jLib.updateGridData(ModifyBill.objGrid, update_data);
                         document.getElementById('bill-component-form').reset();
                         $.validationEngine.closePrompt('.formError',true)
            		       //$.colorbox.close();
                         ModifyBill.component_row_id = null;
                         ModifyBill.component_tr.remove();
                         ModifyBill.component_tr = null;
                        
                         jLib.builPopUpPrompt('.bill-component-prompt',response.mesg,'pass',false);
                         jLib.setFeedback(response.mesg, 'success_message', false);
                   }
                   else {
                        jLib.builPopUpPrompt('.bill-component-prompt',response.mesg,'error',false);
                        jLib.setFeedback(response.mesg, 'error_message', false);
                   }
               },'json');
            }
         });
   },
   
   
   ///////// ********** Bill Application ************ /////////////////////////
   
   applyBill: function(row_ids){
         var load_id = row_ids[0];
         var url = $('#load-apply-bill-url').val();
         var query = 'ids=' + load_id;
         ModifyBill.selected_row_id = load_id;
         $.post(url, query, function(response){  
    		   $("#applybill_colorbox").html(response);
               
               $('table.list-table-data tbody tr:even').addClass('table_zebra');  
               
               $.colorbox({
                 inline:true,
                 scrolling:false,
                 overlayClose:false,
                 escKey:false,
                 title:'Apply Bill',
                 href:"#applybill_colorbox",
                 width:"75%", 
                 height:"50%"
              });
              
              $.colorbox.resize();
         },'html');
   },
   
   
   doApplyBill: function (type){
  	   var selected_values = new Array();
       var selected_tr = new Array();
       var url = $('#do-apply-bill-url').val();
       var chkSelector = ' tr td:nth-child(1) input[type="checkbox"]:checked';
       $('table#applybill-table-data ' + chkSelector).each(function(){
             selected_values.push($(this).val());
             selected_tr.push($(this).parent().parent());
       });
       if(selected_values.length == 0){
            jAlert("At least 1 Record needs to be selected prior to this action",'Alert');
            return false;
       }
       jConfirm('Are you sure you want to continue ?', 'Confirm', function(confirmation) {
            if(confirmation){
                $.post(url, {'ids[]': selected_values,'type':type,'bill_id':ModifyBill.selected_row_id},function(response){
                      if(response.code == 0){
                         var td_txt = 'Not Applied';
                         if(type == 'apply'){
                            td_txt = 'Applied';
                         }
                         for(var tr in selected_tr){
                            $(selected_tr[tr]).find('td:nth-child(5)').html(td_txt);
                         }
                         jLib.builPopUpPrompt('.apply-prompt',response.mesg,'pass',false);
                         jLib.setFeedback(response.mesg,'success_message',false);
                      }
                      else if(response.code == 1){
                         jLib.builPopUpPrompt('.apply-prompt',response.mesg,'error',false);
                         jLib.setFeedback(response.mesg,'error_message',false);
                      }
                },"json");
            }
        });    
   }, 
   
   
   printBill: function(row_ids){
         var load_id = row_ids[0];
         var url = $('#load-print-bill-url').val();
         var query = 'ids=' + load_id;
         ModifyBill.selected_row_id = load_id;
         $.post(url, query, function(response){  
    		   $("#printbill_colorbox").html(response);
               
               $('table.list-table-data tbody tr:even').addClass('table_zebra');  
               
               $.colorbox({
                 inline:true,
                 scrolling:false,
                 overlayClose:false,
                 escKey:false,
                 title:'Print Bill',
                 href:"#printbill_colorbox",
                 width:"75%", 
                 height:"50%"
              });
              
              $.colorbox.resize();
         },'html');
   },
   
   
   doPrintBill: function (){
  	   var selected_values = '';
       //var selected_tr = new Array();
       var url = $('#do-apply-bill-url').val();
       var chkSelector = ' tr td:nth-child(1) input[type="checkbox"]:checked';
       $('table#print-table-data ' + chkSelector).each(function(){
             selected_values += $(this).val()+',' ;
             //selected_tr.push($(this).parent().parent());
       });
       if(selected_values.length == 0){
            jAlert("At least 1 Record needs to be selected prior to this action",'Alert');
            return false;
       }
       
       $("#popUpform #bill_id").val(ModifyBill.selected_row_id);
       $("#popUpform #ids").val(selected_values);
       
       window.open('',"PrintWindow","menubar=yes, width=800, height=500,location=no,status=no,scrollbars=yes,resizable=yes");
       document.getElementById('popUpform').submit();
       
       //alert($("#popUpform #bill_id").val())
       // alert($("#popUpform #ids").val())
       /** 
         $.post(url, {'ids[]': selected_values,'type':type,'bill_id':ModifyBill.selected_row_id},function(response){
                      if(response.code == 0){
                         var td_txt = 'Not Applied';
                         if(type == 'apply'){
                            td_txt = 'Applied';
                         }
                         for(var tr in selected_tr){
                            $(selected_tr[tr]).find('td:nth-child(5)').html(td_txt);
                         }
                         jLib.builPopUpPrompt('.apply-prompt',response.mesg,'pass',false);
                         jLib.setFeedback(response.mesg,'success_message',false);
                      }
                      else if(response.code == 1){
                         jLib.builPopUpPrompt('.apply-prompt',response.mesg,'error',false);
                         jLib.setFeedback(response.mesg,'error_message',false);
                      }
                },"json");
       */ 
   }, 
   
   
   
   initializeFormSelectChange: function(){
        $('#bill-form #property_group_id').change(function(){
            ModifyBill.processGroupChange(parseInt($(this).val()));
            ModifyBill.filterPropertyForm($(this).val());
        });
        $('#bill-form #property_group_id').change();
        
        $('#bill-form #property_group_type_id').change(function(){
            ModifyBill.processGroupTypeChange(parseInt($(this).val()));
        });
   },
   
   processGroupChange: function(value){
        if(value == null){
            return false;
        }
        
        var select_1 = document.getElementById('property_group_type_id');
        select_1.options.length = 0; 
        
        var select_2 = document.getElementById('property_group_sub_type_id');
        select_2.options.length = 0;

        var groupData = gblPrpGroupData[value];
        if(typeof groupData == 'undefined'){
            return false;
        }
        
        var groupTypeSet = false;
        if(groupData['group_type'] != null ){
            groupTypeSet = groupData['group_type'];
        }
        
       // console.log(groupTypeSet);
        
        var groupSubTypeSet = false;
        for(nx in groupTypeSet){
           if(groupTypeSet[nx].group_sub_type != null){
                groupSubTypeSet = groupTypeSet[nx].group_sub_type;
           }
           break;
        }
        //console.log(groupSubTypeSet);
        //Now Populate them
        if(groupTypeSet){            
            for(nx in groupTypeSet){
                var opt = document.createElement('option');
                opt.value = groupTypeSet[nx].id;
                opt.text = groupTypeSet[nx].type_name;		   
                try{ //Standard
                    select_1.add(opt,null) ;
                }
                catch(error){ //IE Only
                    select_1.add(opt) ;
                }   
            }
        }
        else{
            var opt = document.createElement('option');
            opt.value = 0;
            opt.text = 'All';		   
            try{ //Standard
                select_1.add(opt,null) ;
            }
            catch(error){ //IE Only
                select_1.add(opt) ;
            }   
        }
        
        if(groupSubTypeSet){
            for(nx in groupSubTypeSet){
                var opt = document.createElement('option');
                opt.value = groupSubTypeSet[nx].id;
                opt.text = groupSubTypeSet[nx].sub_type_name;		   
                try{ //Standard
                    select_2.add(opt,null) ;
                }
                catch(error){ //IE Only
                    select_2.add(opt) ;
                }   
            }
        }
        else{
            var opt = document.createElement('option');
            opt.value = 0;
            opt.text = 'All';		   
            try{ //Standard
                select_2.add(opt,null) ;
            }
            catch(error){ //IE Only
                select_2.add(opt) ;
            }  
        }
   },
   
   processGroupTypeChange: function(value){
        var group_id = parseInt($('#property_group_id').val());
        var groupData = gblPrpGroupData[group_id];
        var select = document.getElementById('property_group_sub_type_id');
        select.options.length = 0;
        
        if(value == null){
           
           return false;
        }
        
        if(typeof groupData == 'undefined'){
            return false;
        }
        
        
        if(typeof groupData['group_type'] != 'undefined' && groupData['group_type'] != null){
            var groupTypeSet = groupData['group_type'][value];
            var groupSubTypeSet = false;
            if( typeof groupTypeSet != 'undefined' &&  groupTypeSet['group_sub_type'] != null ){
                groupSubTypeSet = groupTypeSet['group_sub_type'];
            }
            //Now Populate them
            if(groupSubTypeSet){
             
                for(nx in groupSubTypeSet){
                    var opt = document.createElement('option');
                    opt.value = groupSubTypeSet[nx].id;
                    opt.text = groupSubTypeSet[nx].sub_type_name;		   
                    try{ //Standard
                        select.add(opt,null) ;
                    }
                    catch(error){ //IE Only
                        select.add(opt) ;
                    }   
                }
            }
            else{
                var opt = document.createElement('option');
                opt.value = 0;
                opt.text = 'All';		   
                try{ //Standard
                    select.add(opt,null) ;
                }
                catch(error){ //IE Only
                    select.add(opt) ;
                } 
            }
        }
        else{
            var opt = document.createElement('option');
                opt.value = 0;
                opt.text = 'All';		   
                try{ //Standard
                    select.add(opt,null) ;
                }
                catch(error){ //IE Only
                    select.add(opt) ;
                } 
        }
        
   },
   
   filterPropertyForm: function(value){
      // IE fix
        if(typeof value == 'string'){}
        else{
            value = '1';
        }
        //console.log(typeof value);
        
       $('#bill-form div.content div.row').each(function(){
            $(this).css('display','block');
       });  
       var groupData = gblPrpGroupData[value];
       var fields = groupData.fields;
       if(fields.length > 0){
            var diff_arr = jLib.array_diff(fields, gblFields)
            for(var x = 0; x < diff_arr.length; x++){
                var diff = diff_arr[x];
                //console.log(diff);
                $('#bill-form div.content div.'+diff+'').css('display','none'); 
            }
       }
       $.colorbox.resize();
   },
   
};

/* when the page is loaded */
$(document).ready(function() {
	ModifyBill.init();
});